import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import api from '../../service/api';
import {AtButton, AtIcon} from 'taro-ui';


import './index.less'

export default class Login extends Component {


  constructor() {
    super(...arguments)
    this.state = {
      isLogin:false
    }
  }

  AskingQuestions() {
  }

  componentWillMount(){
    if(Taro.getStorageSync('loginInfo')){
      this.setState({
        isLogin:true
      })
      if(Taro.getStorageSync('loginInfo').role == 2){
        Taro.redirectTo({
          url:`/pages/DoctorSystem/index`
        })
      }
    }else{
      this.setState({
        isLogin:false
      })
    }
  }

  //获取用户信息
  getUserInfo(userInfo){
    if(userInfo.detail.userInfo)
      Taro.showLoading({
        title: 'loading',
        mask:true
      })
    //登录获取code
    Taro.login().then(res=>{
      const params = {}
      params.nickName = userInfo.detail.userInfo.nickName
      params.headImage = userInfo.detail.userInfo.avatarUrl
      params.code = res.code
      api.post('/inquiry/wxLogin', params).then(res=>{
        //获取用户问诊次数
        Taro.setStorage({
          key:'nowCount',
          data:res.data.data.nowCount
        })
        //储存登录用户信息
        Taro.setStorage({key : 'loginInfo',data:res.data.data}).then(res =>{
          if(Taro.getStorageSync('loginInfo')){
            this.setState({
              isLogin:true
            })
            Taro.hideLoading()
            //用role为2跳转医生端
            if(Taro.getStorageSync('loginInfo').role == 2){
              Taro.redirectTo({
                url:`/pages/DoctorSystem/index`
              })
            }
            Taro.showToast({
              title: '成功',
              icon: 'success',
              duration: 2000
            })
          }
        })
      })
    })
  }

  render() {
    let show = null
    if(!this.state.isLogin){
       show =  (
        <View className='login'>
          <View className='login-bg'></View>
          <View  className='login-box'>
            <View className='login-box-text'>
              请先授权登录
            </View>
            <View className='login-box-btnWidth'>
              <AtButton className='login-box-btn' openType='getUserInfo' onGetUserInfo={this.getUserInfo.bind(this)}>
                  <AtIcon prefixClass='icon' value='wechat' size='16'></AtIcon>
                  <Text className='login-box-btn-text'>微信授权登录</Text>
              </AtButton>
            </View>
          </View>
        </View>
       )
    }else{
       show = (
        <View></View>
       )
    }
    return (
      <View>
        {show}
      </View>
    )
  }
}
